//
//  DownloadImage.m
//  NaRiLSVMT
//
//  Created by zhangmeng on 14-9-8.
//  Copyright (c) 2014年 helloyouth.org. All rights reserved.
//

#import "DownloadImage.h"
#import "FileManager.h"
#import "Network_Operation.h"
#define  PATH [NSString stringWithFormat:@"%@/downimage/",[FileManager getLibraryDirectory]]
#define ARRMAX 40
@implementation DownloadImage
+ (id)sharedInstance
{
    static DownloadImage *singleton = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singleton = [[[self class] alloc] init];
        //singleton.CacheImageArr = [NSMutableArray array];
        [singleton creatDownPath];
    });
    return singleton;
}
-(UIImage *)getUrlImage:(NSString *)templated Block:(void (^)(UIImage *))callback
{
   // WeakSelf;
    if(templated){
    NSString *url = [NSString stringWithFormat:@"%@/%@/%@.png",kBaseUrl,@"player_image",templated];
    NSString *imagePath = [NSString stringWithFormat:@"%@%@.png",PATH,templated];
    __block UIImage *image = nil;
    //取一级缓存
//    [self.CacheImageArr enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL *stop) {
//        if(dic[imagePath]){
//            image = dic[imagePath];
//        }
//    }];
    //取二级缓存
    if(!image){
        if([[NSFileManager defaultManager] fileExistsAtPath:imagePath]){
            
            @try {
                image = [UIImage imageWithContentsOfFile:imagePath];
            }
            @catch (NSException *exception) {
                image = nil;
            }
            @finally {
               // image = nil;
            }
           
//            if(image){
//            NSDictionary *dic = @{imagePath:image};
//            if([wself.CacheImageArr count] >= ARRMAX){
//                [wself.CacheImageArr insertObject:dic atIndex:ARRMAX - 1];
//            }
//            else{
//            [wself.CacheImageArr addObject:dic];
//            }
//            }
        }
    }
    //后台取数据
    if(!image){
     dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    AFHTTPRequestOperation *op = [Network_Operation downloadOperation_Url:url FilePath:imagePath];
    [op start];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        //下载成功 压缩图片
        @try {
            image = [UIImage imageWithContentsOfFile:imagePath];
        }
        @catch (NSException *exception) {
            image = nil;
        }
        @finally {
            //image = nil;
        }
        if(!image){
            NSFileManager *file = [NSFileManager defaultManager];
            NSError *errer = nil;
            if([file removeItemAtPath:imagePath error:&errer]){
                NSLog(@"success");
            }
            else{
                NSLog(@"file");
            }
        }
        else{
        image = [Common imageWithImage:image scaledToSize:CGSizeMake(1024, 157)];
        //图片的压缩
        NSData *imageData = UIImageJPEGRepresentation(image, 0.0001);
        //插入二级缓存
       [imageData writeToFile:imagePath atomically:YES];
        
        image = [UIImage imageWithContentsOfFile:imagePath];
        }
                //插入一级缓存
//        NSDictionary *dic = @{imagePath:image};
//        if([wself.CacheImageArr count] >= ARRMAX){
//            [wself.CacheImageArr insertObject:dic atIndex:ARRMAX - 1];
//        }
//        else{
//            [wself.CacheImageArr addObject:dic];
//        }
    
        callback(image);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSFileManager *file = [NSFileManager defaultManager];
        NSError *errer = nil;
        if([file removeItemAtPath:imagePath error:&errer]){
            NSLog(@"success");
        }
        else{
         NSLog(@"file");
        }
        //[[FileManager sharedInstance]]
    }];
     });
    }
    return image;
    }
    else{
        return nil;
    }
}
//创建存储数据的文件夹
-(void)creatDownPath
{
    NSFileManager *file = [NSFileManager defaultManager];
//    NSString *path = [NSString stringWithFormat:@"%@/downimage/",[FileManager getLibraryDirectory]];
    
    if(![file fileExistsAtPath:PATH]){
        [[FileManager sharedInstance] creatDirectory:PATH];
    }
}
@end
